﻿using LmgCMS.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace LmgCMS.Middleware
{
    /// <summary>
    /// 模板映射过滤器
    /// </summary>
    public class TempleteFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 重写过滤器方法
        /// </summary>
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            //如果是视图控制器，才需要映射到模板
            var viewResult = filterContext.Result as ViewResult;
            if (viewResult != null)
            {
                string DirPath = "main";
                string currDomain = filterContext.HttpContext.Request.Host.Host;//获取当前域名
                var currSite = HttpHelper.GetCurrSite(currDomain);
                if (currSite!=null)
                {
                    DirPath = string.IsNullOrWhiteSpace(currSite.SiteDir) ? "main" : currSite.SiteDir;
                }
                var currentUserTemplate = $"/Views/{DirPath}";
                var controller = filterContext.RouteData.Values["Controller"]?.ToString();
                var action = filterContext.RouteData.Values["Action"]?.ToString();
                var channelName = filterContext.RouteData.Values["channelName"]?.ToString();
                if (channelName != null)
                {
                    viewResult.ViewName = string.Format("{0}/{1}/{2}.cshtml", currentUserTemplate, channelName, action);
                }
                else
                {
                    viewResult.ViewName = string.Format("{0}/{1}/{2}.cshtml", currentUserTemplate, controller, action);
                }
                return;
            }

            base.OnResultExecuting(filterContext);
        }
    }

}
